<template>
  <view>
    <up-input
      placeholder="DD19L"
      :border="'surround'"
      :modelValue="modelValue?.alias?modelValue?.alias:modelValue?.value"
      @click="show = true"
    >
      <template #prefix>
        <up-text
          text="簡稱："
          margin="0 3px 0 0"
          color="#323233"
        ></up-text>
      </template>
    </up-input>

    <!-- 弹出层 -->
    <up-popup
      class="cartPopup"
      :safeAreaInsetTop="true"
      :show="show"
      :round="10"
      @close="close"
      @open="open"
    >
      <view class="content p-4" :style="adaptiveStyle">
        <u-search
          v-model="searchText"
          :searchIcon="MapIcons.search"
            :adjust-position="false"
          :placeholder="searchPlaceholder"
          :showAction="false"
        :focus="true"
        ></u-search>

        <scroll-view style="height: 40vh;" scroll-y>
          <view
            v-for="item in options"
            :key="item.code"
            class="py-3 px-4 border-bottom"
            @click="selectItem(item)"
          >
            {{ item.customerCode ? item.customerCode : item.code }}
              <up-gap height="5" bgColor="#ffffff00"></up-gap>
            <span style="color:#8e8e8e">{{ item.customerDescription ? item.customerDescription : item.description }}</span>
          </view>
        </scroll-view>
      </view>
    </up-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits, onMounted,onUnmounted } from 'vue'
import { HKMAPgetLotType } from '@/api/system/map'
import { useKeyboard } from '@/utils/useKeyboard'
import { MapIcons } from '@/utils/base64-icons'

// Props 定义
const props = defineProps<{
  modelValue: { value: any ,alias: any ,label?:any} | null
  label?: string
  placeholder?: string
  searchPlaceholder?: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: { value: any, alias: any, label?: any }): void
  (e: 'change', value: any): void
}>()

const show = ref(false)
const searchText = ref('')
const options = ref<Array<{ code: string; customerCode: string; description: any ; customerDescription: string}>>([])
const loading = ref(false)

// 使用全局键盘状态管理
const { keyboardHeight, isKeyboardVisible, adaptiveStyle } = useKeyboard({
  autoStart: false, // 不自动启动，由组件控制
  autoStop: false,  // 不自动停止，由组件控制
  styleConfig: {
    type: 'margin',
    direction: 'bottom'
  },
  onChange: (state) => {
    // console.log('SearchPicker keyboard state changed:', state)
  }
})


onMounted(() => {
  if (props.modelValue?.value) {
    searchText.value = props.modelValue?.alias?props.modelValue?.alias:props.modelValue?.value;
  }
})

async function fetchOptions(keyword = '') {
  loading.value = true
    if (keyword?.length<1) {
      options.value = []
      return
    }
    HKMAPgetLotType(keyword).then((data:any) => {
      options.value = data.rows;
      if(data.rows.length>0 && data.rows[0].code==props.modelValue?.value && props.modelValue?.label==""){
        emit('update:modelValue', {
          value: data.rows[0].code,
          alias: data.rows[0].customerCode?data.rows[0].customerCode:data.rows[0].code ,
          label:data.rows[0].description
        })
      }
      loading.value = false
    }).catch(error => {
      options.value = [];
      loading.value = false
      console.error("获取数据失败:", error);
    })
}

// 监听搜索关键词变化
watch(searchText, (val) => {
  fetchOptions(val)
})

// 打开弹窗时首次加载
function open() {
  show.value = true
  // console.log('SearchPicker opened')
  searchText.value = props.modelValue?.alias ? props.modelValue?.alias : props.modelValue?.value
}

function close() {
  searchText.value = '';
  show.value = false
}

function selectItem(item: any) {
  searchText.value = item.customerCode?item.customerCode:item.code;
  emit('update:modelValue', {value: item.code,alias: item.customerCode,label:item.description})
  emit('change', item)
  show.value = false
}


</script>

<style scoped>
.border-bottom {
  border-bottom: 1px solid #eee;
}

.cartPopup .content {
  padding: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  height: 40vh;
}

.py-3 {
  padding-top: 20rpx;
  padding-bottom: 20rpx;
}
.px-4 {
  padding-left: 30rpx;
  padding-right: 30rpx;
}
.p-4 {
  padding: 30rpx;
}
</style>
